import java.util.Deque;
import java.util.LinkedList;
import java.util.List;

/**
 * Created with IntelliJ IDEA.
 * Description: leetcode: LCR 046. 二叉树的右视图
 * <a href="https://leetcode.cn/problems/WNC0Lk/description/">...</a>
 * User: DELL
 * Date: 2023-10-21
 * Time: 22:29
 */

class TreeNode {
    int val;
    TreeNode left;
    TreeNode right;

    TreeNode() {
    }

    TreeNode(int val) {
        this.val = val;
    }

    TreeNode(int val, TreeNode left, TreeNode right) {
        this.val = val;
        this.left = left;
        this.right = right;
    }
}

public class Solution {
    /**
     * 解题思路: (层序遍历)
     * 使用队列进行二叉树的层序遍历,同时每次都取最后一个节点,将其值记录下来即可
     *
     * @param root
     * @return
     */
    public List<Integer> rightSideView(TreeNode root) {
        List<Integer> res = new LinkedList<>();
        // 非空校验
        if (root == null) {
            return res;
        }
        // 辅助队列
        Deque<TreeNode> queue = new LinkedList<>();
        // 根节点入队列
        queue.add(root);
        while (!queue.isEmpty()) {
            int size = queue.size();
            // 先将前 size -1 个节点出队列
            while (--size != 0) {
                TreeNode cur = queue.poll();
                if (cur.left != null) {
                    queue.offer(cur.left);
                }
                if (cur.right != null) {
                    queue.offer(cur.right);
                }
            }
            // 将最后一个节点出队列并将其值加入 res 中
            TreeNode last = queue.poll();
            res.add(last.val);
            if (last.left != null) {
                queue.offer(last.left);
            }
            if (last.right != null) {
                queue.offer(last.right);
            }
        }
        return res;
    }
}